/*
 * WindowExplorerFrame.java
 *
 * Created on March 21, 2009, 3:37 PM
 */
package Control;

import java.io.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

/**
 *
 * @author  NHAnh
 */
public class MiniTotalCommanderControl {

    /* http://courses.cs.hcmus.edu.vn/mod/forum/discuss.php?d=3348
     *
     * @param String pathFile: duong dan tuyet doi den file can tao moi.
     * @throws java.io.IOException
     */
    /**
     *
     * @param pathFile
     * @throws java.io.IOException
     */
    public static void runFile(String pathFile) throws IOException {
        //new File(pathFile);
        String program = "C:\\WINDOWS\\system32\\notepad.exe";
        Runtime myCommand = java.lang.Runtime.getRuntime();
        myCommand.exec(program + " " + pathFile);
    }

    /** View mot file
     *
     * @param file
     * @throws java.io.IOException
     */
    public static void viewFile(File file) throws IOException {
        if(file.isDirectory())
            return;
        JFrame frame = new JFrame(file.getName());
        JPanel panel = new JPanel();
        JTextArea jt = new JTextArea("Welcome Roseindia", 5, 20);
        FileInputStream finp = new FileInputStream(file);

        ByteArrayOutputStream bStrm = new ByteArrayOutputStream();
        int ch;
        while ((ch = finp.read()) != -1) {
            bStrm.write(ch);
        }

        String str = new String(bStrm.toByteArray());
        bStrm.close();

        finp.close();

        jt.setText(str);
        jt.setEnabled(false);
        frame.add(panel);
        panel.add(jt);

        frame.setSize(250, 200);
        frame.setVisible(true);
        //frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
    }

    /**Mo va sua chua file bang notepad
     *
     * @param file
     * @return
     * @throws java.io.IOException
     */
    public static boolean editFile(File file) throws IOException {
        if (file.isFile()) {
            String program = "C:\\WINDOWS\\system32\\notepad.exe";
            String pathfile = file.getPath();
            Runtime myCommand = java.lang.Runtime.getRuntime();
            myCommand.exec(program + " " + pathfile);
            return true;
        }
        return false;

    }

    /**Mo va sua chua file bang notepad
     *
     * @param pathFile
     * @throws java.io.IOException
     */
    public static void editFile(String pathFile) throws IOException {
        File file = new File(pathFile);
        editFile(file);
    }

    /**Doi ten file hay folder
     *
     * @param file
     * @param newName
     */
    public static void rename(File file, String newName) {
        File newfile = new File(file.getParentFile(), newName);
        file.renameTo(newfile);
    }

    /** Tao moi mot hoac nhieu folder
     *
     * @param pathFolder
     */
    public static void newFolder(String pathFolder) {
        (new File(pathFolder)).mkdirs();
    }

    /**Copy tu file den file
     *
     * @param source
     * @param dest
     * @throws java.io.IOException
     */
    public static void copyFile(File source, File dest) throws IOException {
        if (!dest.exists()) {
            dest.createNewFile();
        }
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new FileInputStream(source);
            out = new FileOutputStream(dest);
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            in.close();
            out.close();
        }
    }

    /**Copy tu file den file
     *
     * @param pathSource
     * @param pathDest
     * @throws java.io.IOException
     */
    public static void copyFile(String pathSource, String pathDest) throws IOException {
        File source = new File(pathSource);
        File dest = new File(pathDest);
        copyFile(source, dest);
    }

    /**Copy tu folder den folder
     *
     * @param sourceDir
     * @param destDir
     * @throws java.io.IOException
     */
    public static void copyDirectory(File sourceDir, File destDir) throws IOException {
        if (!destDir.exists()) {
            destDir.mkdir();
        }
        File[] children = sourceDir.listFiles();
        for (File sourceChild : children) {
            String name = sourceChild.getName();
            File destChild = new File(destDir, name);
            if (sourceChild.isDirectory()) {
                copyDirectory(sourceChild, destChild);
            } else {
                copyFile(sourceChild, destChild);
            }
        }
    }

    /**Copy tu folder den folder
     *
     * @param pathSource 
     * @param pathDest
     * @throws java.io.IOException
     */
    public static void copyDirectory(String pathSource, String pathDest) throws IOException {
        File source = new File(pathSource);
        File dest = new File(pathDest);
        copyDirectory(source, dest);
    }

    /**Copy tu file den folder
     *
     * @param sourceFile
     * @param destDir
     * @throws java.io.IOException
     */
    public static void copyFile2Directory(File sourceFile, File destDir) throws IOException {
        String name = sourceFile.getName();
        File fileDest = new File(destDir, name);
        copyFile(sourceFile, fileDest);
    }

    /**Copy tu file den folder
     *
     * @param pathSource 
     * @param pathDest
     * @throws java.io.IOException
     */
    public static void copyFile2Directory(String pathSource, String pathDest) throws IOException {
        File source = new File(pathSource);
        File dest = new File(pathDest);
        copyFile2Directory(source, dest);
    }

    /**Copy chuan khong phan biet nguon la file hay folder
     *
     * @param source 
     * @param dest
     * @throws java.io.IOException
     */
    public static void copy(File source, File dest) throws IOException {
        if (source.isDirectory()) {
            copyDirectory(source, dest);
        } else {
            copyFile2Directory(source, dest);
        }
    }

    /**Copy chuan khong phan biet nguon la file hay folder
     *
     * @param pathSource
     * @param pathDest
     * @throws java.io.IOException
     */
    public static void copy(String pathSource, String pathDest) throws IOException {
        File source = new File(pathSource);
        File dest = new File(pathDest);
        copy(source, dest);
    }

    /**Delete file hay folder
     *
     * @param resource
     * @return True: Thanh cong False: That bai
     * @throws java.io.IOException
     */
    public static boolean delete(File resource) throws IOException {
        if (resource.isDirectory()) {
            File[] childFiles = resource.listFiles();
            for (File child : childFiles) {
                delete(child);
            }
        }
        return resource.delete();
    }

    /**Delete file hay folder
     *
     * @param pathResource
     * @return True: Thanh cong False: That bai
     * @throws java.io.IOException
     */
    public static boolean delete(String pathResource) throws IOException {
        File resource = new File(pathResource);
        return delete(resource);
    }

    /**Di chuyen file hoac folder den folder
     *
     * @param source 
     * @param dest
     * @throws java.io.IOException
     */
    public static void move(File source, File dest) throws IOException {
        if (source.isDirectory()) {
            copyDirectory(source, dest);
        } else {
            copyFile2Directory(source, dest);
        }
        delete(source);
    }

    /**Di chuyen file hoac folder den folder
     *
     * @param pathSource
     * @param pathDest
     * @throws java.io.IOException
     */
    public static void move(String pathSource, String pathDest) throws IOException {
        File source = new File(pathSource);
        File dest = new File(pathDest);
        move(source, dest);
    }

//Zip file, slide IO NHAnh
    /**Nen mot file hoac folder thanh file nen co duoi .zip
     *
     * @param File file: file can nen co the la file hay folder
     * @param String nameFileZip: ten file sau khi nen co duoi la ".zip"
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public static void zipFile(File file, String nameFileZip) throws FileNotFoundException, IOException {
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.getParent() + nameFileZip));
        String pathzipentry = "";
        zipFile(file, zos, pathzipentry);
    }

    /**Dung de dua file hay cau truc cua mot folder vao ZipOutputStream de thanh file nen
     *
     * @param File file: file hay folder can nen
     * @param ZipOutputStream zos: Chua cac entry la cau truc cua file zip, dung de ghi ra file zip
     * @param String pathzipentry: Duong dan tuong doi trong file zip cua cac entry
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public static void zipFile(File file, ZipOutputStream zos, String pathzipentry) throws FileNotFoundException, IOException {
        if (file.isFile()) {
            zipFileEntry(file, zos, pathzipentry);
        } else {
            zipFolderEntry(file, zos, pathzipentry);
        }

        zos.closeEntry();
    //zos.flush();
    //zos.close();
    }

    /**Tao mot entry tuong ung voi mot file la file va nen file do lai vao zos
     *
     * @param File file: file hay folder can nen
     * @param ZipOutputStream zos: Chua cac entry la cau truc cua file zip, dung de ghi ra file zip
     * @param String pathzipentry: Duong dan tuong doi trong file zip cua cac entry
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public static void zipFileEntry(File file, ZipOutputStream zos, String pathzipentry) throws FileNotFoundException, IOException {
        byte[] data = new byte[1024];
        //ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(file.getParent() + nameFileZip));
        FileInputStream fis = new FileInputStream(file);
        zos.putNextEntry(new ZipEntry(pathzipentry + file.getName()));
        int count;
        while ((count = fis.read(data, 0, 1024)) != -1) {
            zos.write(data, 0, count);
        }
        zos.closeEntry();
    //zos.flush();
    //zos.close();
    }

    /**Tao mot entry tuong ung voi mot file la folder, va duyet vao sau trong folder vua nen.
     *
     *@param File file: file hay folder can nen
     * @param ZipOutputStream zos: Chua cac entry la cau truc cua file zip, dung de ghi ra file zip
     * @param String pathzipentry: Duong dan tuong doi trong file zip cua cac entry
     * @throws java.io.IOException
     */
    public static void zipFolderEntry(File folder, ZipOutputStream zos, String pathzipentry) throws IOException {
        String temp_pathzipentry = pathzipentry + folder.getName() + "/";
        zos.putNextEntry(new ZipEntry(temp_pathzipentry));
        zos.closeEntry();
        File[] arrFilesChild = folder.listFiles();
        zipFiles(arrFilesChild, zos, temp_pathzipentry);
    }

    /**Nen mot mang cac file khong phan biet la folder hay file thanh file zip co ten la nameFileZip
     *
     * @param File [] files: Mang cac file khong phan biet folder hay file can nen
     * @param String nameFileZip: ten file sau khi nen
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public static void zipFiles(File[] files, String nameFileZip) throws FileNotFoundException, IOException {
        String pathzipentry = "";
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(files[0].getParent() + "\\" + nameFileZip));

        zipFiles(files, zos, pathzipentry);

        zos.flush();
        zos.close();
    }

    /**Dua mot mang cac file khong phan biet la folder hay file vao zos
     *
     * @param File [] arrFiles: Mang cac file khong phan biet folder hay file can nen
     * @param ZipOutputStream zos: Chua cac entry la cau truc cua file zip, dung de ghi ra file zip
     * @param String pathzipentry: Duong dan tuong doi trong file zip cua cac entry
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public static void zipFiles(File[] arrFiles, ZipOutputStream zos, String pathzipentry) throws FileNotFoundException, IOException {
        for (int i = 0; i < arrFiles.length; i++) {
            zipFile(arrFiles[i], zos, pathzipentry);
        }
    }

    /**Lay cac entry.getName() cua file zip ra dua vao mot mang cac chuoi
     *
     * @param ArrayList<String> pathZipEntrys: Mang cac duong dan tuong doi cua entry
     * @param ZipFile fileZip: file zip can trich xuat entry
     */
    public static void explorerZip(ArrayList<String> pathZipEntrys, ZipFile fileZip) {
        Enumeration entries = fileZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            pathZipEntrys.add(entry.getName());
        }
    }

    /**Lay cac entry.getName() cua file zip ra dua vao mot mang cac chuoi
     *
     * @param ArrayList<String> pathZipEntrys: Mang cac duong dan tuong doi cua entry
     * @param File file: file zip can trich xuat entry
     * @throws java.util.zip.ZipException
     * @throws java.io.IOException
     */
    public static void explorerZip(ArrayList<String> pathZipEntrys, File file) throws ZipException, IOException {
        ZipFile fileZip = new ZipFile(file);
        Enumeration entries = fileZip.entries();
        while (entries.hasMoreElements()) {
            ZipEntry entry = (ZipEntry) entries.nextElement();
            pathZipEntrys.add(entry.getName());
        }
    }

    /**
     *
     * @param file
     * @param appendFiles
     * @param pathzipentry
     * @throws java.util.zip.ZipException
     * @throws java.io.IOException
     */
    public static void appendZipFile(File file, File[] appendFiles, String pathzipentry) throws ZipException, IOException {
        FileInputStream fis = null;
        byte[] data = new byte[1024];
        ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("temp.zip"));
        ZipFile zfile = new ZipFile(file);
        Enumeration entries = zfile.entries();

        while (entries.hasMoreElements()) {

            ZipEntry entry = (ZipEntry) entries.nextElement();
            InputStream is = zfile.getInputStream(entry);
            zos.putNextEntry(entry);
            int count;
            while ((count = is.read(data, 0, 1024)) != -1) {
                zos.write(data, 0, count);
            }
            zos.closeEntry();
            is.close();
            //String t = entry.getName();
            if (entry.getName().compareTo(pathzipentry) == 0) {
                zipFiles(appendFiles, zos, pathzipentry);
            }
        }

        zfile.close();
        zos.flush();
        zos.close();
        String path = file.getPath();
        file.delete();
        File f = new File("temp.zip");
        f.renameTo(new File(path));
    }

    /**
     *
     * @param file
     * @param name
     * @throws java.io.FileNotFoundException
     * @throws java.io.IOException
     */
    public static void unZip(File file, String name) throws FileNotFoundException, IOException {
        ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
        ZipEntry entry;
        File temp = new File(file.getParent() + "\\" + name);
        temp.mkdir();


        while ((entry = zis.getNextEntry()) != null) {
            int count;
            byte data[] = new byte[1024];
            String path = entry.getName();
            String dirs = temp.getPath() + File.separator;
            //String[] s = path.split("\\\\");

            String[] s = path.split("/");
            //Neu ton tai "/" co tao folder, nhung khong biet s[cuoi cung] la file hay folder
            if (path.lastIndexOf("/") != -1) {
                for (int i = 0; i < s.length - 1; i++) {
                    dirs = dirs + s[i] + "/";
                }
                //Neu "/" khong nam o vi tri cuoi cung thi s[cuoi cung] la file
                if (path.lastIndexOf("/") != path.length() - 1) {
                    //s[cuoi cung] se la file
                    new File(dirs).mkdirs();
                } else {
                    //chi toan la folder sau khi tao xong se qua zipentry khac
                    dirs = dirs + s[s.length - 1] + "/";
                    new File(dirs).mkdirs();
                    continue;
                }
            }
            //Giai nen file
            File fout = new File(temp.getPath() + "\\" + path);
            fout.createNewFile();
            FileOutputStream fos = new FileOutputStream(fout);
            while ((count = zis.read(data, 0, 1024)) != -1) {
                fos.write(data, 0, count);
            }
            fos.close();
        }
        zis.close();
    }
}
